package gui;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class LineSizeChooser extends JPanel{
	
	private PencilSampler sampler = new PencilSampler();
	
	private JSpinner jSpinner = new JSpinner();
	
	private int selectedSize = 1;
	
	public LineSizeChooser(){
		
		setPreferredSize(new Dimension(70,80));
		
		GridBagLayout layout = new GridBagLayout();
		
		GridBagConstraints c = new GridBagConstraints();
		
		setLayout(layout);
		
		c.gridx = 0;
		c.gridy = 0;
		c.weighty = 0.2;
		c.weightx = 1;
		c.fill = GridBagConstraints.HORIZONTAL;
		add(jSpinner, c);
		
		c.gridx = 0;
		c.gridy = 1;
		c.weighty = 0.8;
		c.weightx = 1;
		c.fill = GridBagConstraints.BOTH;
		add(sampler, c);
		
		jSpinner.addChangeListener(new ChangeListener() {
			
			@Override
			public void stateChanged(ChangeEvent e) {
				Integer value = (Integer) jSpinner.getValue();
				
				if(value > 0){
					selectedSize = value;
					sampler.repaint();
					fireActionListener();
				}
			}
		});
		
	}
	
	
	
	public int getSelectedSize() {
		return selectedSize;
	}



	public void setSelectedSize(int selectedSize) {
		this.selectedSize = selectedSize;
	}



	public void addActionListener(ActionListener listener){
		this.listenerList.add(ActionListener.class, listener);
	}
	
	private void fireActionListener(){
		
		ActionEvent evt = new ActionEvent(this, ActionEvent.RESERVED_ID_MAX+1, "new size");
		
		for(ActionListener l : this.listenerList.getListeners(ActionListener.class)){
			l.actionPerformed(evt);
		}
	}
	
	private class PencilSampler extends JComponent{
		
		public PencilSampler(){
			setBackground(Color.white);
		}
		
		public void paintComponent(Graphics g){
			
			super.paintComponent(g);
			
			Graphics2D g2 = (Graphics2D) g;
			
			int y = (this.getHeight() - selectedSize) / 2;
			
			int x = this.getInsets().left;
			
			int x2 = this.getWidth() - this.getInsets().right;
			
			BasicStroke stroke = new BasicStroke(selectedSize);
			
			g2.setColor(this.getBackground());
			g2.fillRect(0, 0, this.getWidth(), this.getHeight());
			
			g2.setStroke(stroke);
			g2.setColor(Color.black);
			
			g2.drawLine(x, y, x2, y);
		}
	}
	
	public static void main(String args[]){

		JFrame frm = new JFrame("Teste");
		
		LineSizeChooser sc = new LineSizeChooser();
		
		frm.add(sc);
		frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frm.setSize(500,500);
		frm.setVisible(true);
		
	}

}
